package com.example.interceptor;

import com.example.TokenUtil.JwtUtils;
import com.example.TokenUtil.spiltUtils;
import com.example.userdome.pojo.User;
import com.example.userdome.service.UserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class Interceptor implements HandlerInterceptor {
        @Resource
        private UserService userService;

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            // 获取用户登录凭证
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("token".equals(cookie.getName())) {
                        String token = cookie.getValue();
                        Claims claims;
                        String pe;// 获取用户登录名
                        String uri = request.getRequestURI();
                        log.info("访问uri => " + uri);

                        if (token != null && (claims = JwtUtils.parseJWT(token)) != null && (pe = JwtUtils.getUserName(claims)) != null) {
                            String userName = spiltUtils.getUserName(pe);
                            // 已登录
                            User user = userService.getByUserName(userName);
                            if (user == null) {
                                log.info("用户不存在或被删除");
                                // 已经登录的用户被删除了?
                                return false;
                            }
                            if (user.getStatus()==1){
                                log.info(user.getUsername()+"用户已被禁用！");
                                return false;
                            }
                            // 在这里可以根据需要进行权限验证等操作
                            log.info("鉴权通过 => " + uri);
                            return true;
                        } else {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        }
                        log.info("鉴权失败 => " + uri);
                        return false;
                    }

                }
            }
            return false;
        }
}
